Matlab excel读取到struct

读取excel

  • 先用xlsread读取excel数据到matlab,返回num,txt,raw 三个变量;
  • 获取raw中的第一行作为struct的字段;
  • 将元胞数组 raw 转换为struct,并设置对应字段;
  • 保存文件;

其中,

1
[num,txt,raw] = xlsread(filename,sheet)

返回3个变量,在mat文件中返回 double 数据,在元胞数组 txt 中返回文本字段,在元胞数组 raw 中返回数值数据和文本数据。

完整coding,

1
2
3
4
5
6
7
8
9
10
clc;
clear;
close all;
% read datas from xlsx and returns the text fields in cell array txt,
% and both numeric and text data in cell array raw
[num,txt,raw] = xlsread('test.xlsx','Sheet1');
colHeadings = raw(1,:); % get the columns headings
test = cell2struct(raw(2:end,:),colHeadings,2);
save test.mat test;
clear num txt raw colHeadings test

https://cn.mathworks.com/help/matlab/ref/cell2struct.html?s_tid=gn_loc_drop
https://cn.mathworks.com/help/matlab/ref/xlsread.html?s_tid=gn_loc_drop